package ui.timeline;

import java.awt.event.MouseEvent;

import javax.swing.plaf.basic.BasicSliderUI.TrackListener;



public class OneThumbTimeLineRangeTrackListener extends TrackListener 
{
	private OneThumbTimeLineSliderUI timeLineSliderUI;

	/**
	 * @param timeLineSliderUI
	 */
	
	public OneThumbTimeLineRangeTrackListener(OneThumbTimeLineSliderUI sliderUI)
	{
		sliderUI.super();
		this.setTimeLineSliderUI(sliderUI);
	}

	public OneThumbTimeLineSliderUI getTimeLineSliderUI() {
		return timeLineSliderUI;
	}

	public void setTimeLineSliderUI(OneThumbTimeLineSliderUI timeLineSliderUI) {
		this.timeLineSliderUI = timeLineSliderUI;
	}
	
	@Override
	public void mousePressed(MouseEvent e) 
	{
	  currentMouseX = e.getX();
	  currentMouseY = e.getY();

	  if (this.timeLineSliderUI.getSlider().isRequestFocusEnabled()) {
		  this.timeLineSliderUI.getSlider().requestFocus();
	  }

	  offset = currentMouseX - this.timeLineSliderUI.getThumbRect().x;
	  this.timeLineSliderUI.currentDragging = true;
	  this.timeLineSliderUI.getSlider().setValueIsAdjusting(true);
	  System.out.println(this.timeLineSliderUI.currentDragging);

  }
	@Override
	public void mouseReleased(MouseEvent e) {
		this.timeLineSliderUI.getSlider().setValueIsAdjusting(false);
		this.timeLineSliderUI.currentDragging = false;
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		if (this.timeLineSliderUI.currentDragging)
		{
			currentMouseX = e.getX();
			currentMouseY = e.getY();
			this.timeLineSliderUI.getSlider().setValueIsAdjusting(true);
			moveCurrentThumb();
		}
	}
	
	public void moveCurrentThumb() {
		  int thumbMiddle = 0;
		  int halfThumbWidth = this.timeLineSliderUI.getThumbRect().width / 2;
		  int thumbLeft = currentMouseX - offset;
		  int trackLeft = this.timeLineSliderUI.getTrackRect().x;

		  int trackRight = this.timeLineSliderUI.getTrackRect().x + (this.timeLineSliderUI.getTrackRect().width - 1);
		  int hMax = this.timeLineSliderUI.xPositionForValue( (int) (((OneThumbTimeLineSlider)this.timeLineSliderUI.getSlider()).getCurrentValue() + this.timeLineSliderUI.getSlider().getExtent()));

		  // Apply bounds to thumb position.
		  if (this.timeLineSliderUI.drawInverted()) {
			  trackLeft = hMax;
		  } else {
			  trackRight = hMax;
		  }
		  thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
		  //thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);

		  this.timeLineSliderUI.setThumbLocation(thumbLeft, this.timeLineSliderUI.getThumbRect().y);

		  thumbMiddle = thumbLeft + halfThumbWidth;
		  ((OneThumbTimeLineSlider)this.timeLineSliderUI.getSlider()).setCurrentValue(this.timeLineSliderUI.valueForXPosition(thumbMiddle));
	}
}